package io.nutz.nutzsite.module.common;

import io.nutz.nutzsite.common.base.Globals;
import io.nutz.nutzsite.common.utils.FileUtils;
import io.nutz.nutzsite.common.utils.ShiroUtils;
import io.nutz.nutzsite.common.utils.StringUtils;
import io.nutz.nutzsite.common.utils.UpLoadUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Files;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.nutz.repo.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@IocBean
@At("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @At("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            //System.currentTimeMillis() +
            String realFileName =  fileName.substring(fileName.indexOf("_") + 1);
            String filePath = Globals.getConfig("upload.path") + "/" + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
	/**
	 * 上传文件，存在“用户id”目录中,“用户id-”开头的文件
	 */
	@AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @POST
	//@RequiresPermissions("sys:user:import")
	@At
	@Ok("json")
	public Object upload(@Param("file") TempFile tf,@Param("filetype")  String filetype) {
		NutMap map=NutMap.NEW();
		try {
			String path=UpLoadUtil.upLoadFileSysConfigPath(tf, ShiroUtils.getSysUserId());
			map.addv("code", 0);
			map.addv("msg", "");
			map.addv("data", "");
			map.addv("url", path);
			map.addv("fileName", tf.getSubmittedFileName());
			return map;
		} catch (Exception ex) {
			map.addv("code", 500);
			map.addv("msg", ex.getMessage());
			return map;
		}
	}
	/**
	 * 浏览新上传的图片
	 * @param iname
	 * @param resp
	 * @param req
	 * @return
	 */
	@At("/vimg")
	@Ok("raw")
	public File vimg(@Param("n")String iname, HttpServletResponse resp, HttpServletRequest req) {
		try {
			String f ="";
			int hasuid=iname.indexOf("-");
			if(hasuid==-1) f = Globals.getConfig("upload.path") + "/" + iname;
			else{
				String uid=iname.substring(0, hasuid);
				f= Globals.getConfig("upload.path") + "/"+uid+ "/" + iname;
			}
			 /*log.info("\r\n"+f+"\r\n");*/
			 return new File(f);
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	/**
	 * 浏览以前上传的图片
	 * @param iname
	 * @param resp
	 * @param req
	 * @return
	 */
	@At("/vimg")
	@Ok("raw")
	public File vimg0(@Param("n")String iname, HttpServletResponse resp, HttpServletRequest req) {
		try {
			String f ="";
			int hasuid=iname.indexOf("-");
			if(hasuid==-1) f = Globals.getConfig("upload.path") + "/" + iname;
			else{
				String uid=iname.substring(0, hasuid);
				f= Globals.getConfig("upload.path") + "/"+uid+ "/" + iname;
			}
			 /*log.info("\r\n"+f+"\r\n");*/
			 return new File(f);
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	  /**
	   * 由考试客户端直接上传考生文件夹备份（rar）
	   * @param filename
	   * @param UploadFile
	   * @return
	   */
	  @At
	  @Ok("raw")
	  public String uploadjj(@Param("FileName") String filename, @Param("UploadFile") String UploadFile) {
		  String ksid=filename.split("_")[0];
		  String fname=filename.split("_")[1];
		  Map<String, Object> jsonroot = new HashMap<String, Object>();
		  try {
	             
	            String f = Globals.getConfig("upload.path") + "/" +ksid +"/" +  fname;
	            byte[] t =Base64.decode(UploadFile);
	            //磁盘根目录创建了upload.path配置的相对路径
	            log.debug("\r\n"+f+"==="+UploadFile.length());
	            Files.write(new File(f), t);
	          jsonroot.put("num",1);
	      } catch (Exception e) {
	          e.printStackTrace();
	          jsonroot.put("num",0);
	      }        
			return Json.toJson(jsonroot);
	  }
}
